import React, { Component } from 'react';
import { Message, Dialog, Button, Form, Input, Field, TreeSelect, Select } from '@alifd/next';
import { orgs, insert } from '../../../../api/Org';
import { areas } from '../../../../api/Area';
import { Forest } from '../../../../libs/Tree';
import '../OrgTable.scss';
import eventProxy from '../../../../libs/eventProxy';

const FormItem = Form.Item;

export default class AddDialog extends Component {
  static displayName = 'AddDialog';

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      dataIndex: null,
      dataSource: [],
    };
    this.field = new Field(this);
  }
  
 componentWillMount() {
   this.oth_fields = {
    parentId: null,
    areaId: null,
    type: 0,
  };
 }

 updateSelect(){
  orgs().then((response) => {
    const data = response.data.data;
    const shows = [];
    data.forEach((ele) => {
      shows.push({
        label: ele.name,
        key: ele.id,
        pid: ele.parentId,
        id: ele.id,
        value: ele.id,
        sys_code: ele.systemCode,
      });
    });
    const treeData = this.dataToTree(shows);
    areas().then((areaResp) => {
      const area = areaResp.data.data;
      const areaShow = [];
      area.forEach((ele) => {
        areaShow.push(
          {
              label: ele.name,
              key: ele.id,
              pid: ele.parentId,
              id: ele.id,
              value: ele.id,
          }
        );
        const areaTree = this.dataToTree(areaShow);
        this.setState({
          dataSource: treeData,
          areaSource: areaTree,
          visible: true,
        });
      });
    });
  });
 }
 dataToTree= (dataSource) => {
  const forest = new Forest();
  dataSource.forEach((menu) => {
      menu.pid = menu.pid;
      menu.children = [];
      forest.init(menu);
  });
  return forest.roots;
}

  handleSubmit = () => {
    this.field.validate((errors, values) => {
      if (errors) {
        console.log('Errors in form!!!');
        return;
      }
      const { dataIndex } = this.state;
      values.parentId = this.oth_fields.parentId;
      values.type = this.oth_fields.type;
      values.areaId = this.oth_fields.areaId;
      this.props.getFormValues(dataIndex, values);
     insert(values).then((response) => {
       const data = response.data;
       if (data.code === 200){
         Message.success('添加成功');
         this.setState({
           visible: false,
         });
         eventProxy.trigger('orgs:select:change');
       } else {
         Message.warning('添加失败');
       }
     });
    });
  };

  onOpen = () => {
    this.updateSelect();
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  onSortChange = (value) => {
    this.oth_fields.treeSort = value;
  }

  onAllSortChange = (value) => {
    this.oth_fields.allSort = value;
  }

  onUseableChange = (checked) => {
      this.oth_fields.useable = (checked === true ? 0 : 1);
  }

  handleChange =(value) => {
    this.oth_fields.parentId = value;
  }

  handleAreaChange =(value) => {
    this.oth_fields.areaId = value;
  }
  onSelectChange =(value) => {
    this.oth_fields.type = value;
  }
  render() {
    const init = this.field.init;
    const formItemLayout = {
      labelCol: {
        fixedSpan: 6,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const Option = Select.Option;
    return (
      <div style={styles.editDialog}>
        <Button type="primary" onClick={this.onOpen}>
        新增机构
        </Button>
        <Dialog
          style={{ width: 640 }}
          visible={this.state.visible}
          onOk={this.handleSubmit}
          closeable="esc,mask,close"
          onCancel={this.onClose}
          onClose={this.onClose}
          title="新增"
        >
          <Form field={this.field} {...formItemLayout}>

            <FormItem label="上级机构：" {...formItemLayout}>
              <TreeSelect treeDefaultExpandAll 
                dataSource={this.state.dataSource} 
                onChange={this.handleChange} 
                style={{ width: 220 }} 
              />
            </FormItem>

            <FormItem label="机构名称：">
              <Input
                {...init('name', {
                  rules: [{ required: true, message: '必填选项' }],
                })}
              />
            </FormItem>

            <FormItem label="机构类型：" {...formItemLayout}>
              <Select id="basic-demo" onChange={this.onSelectChange} defaultValue="0">
                <Option value="0">机构</Option>
                <Option value="1">部门</Option>
              </Select>
            </FormItem>

            <FormItem label="所属区域：" {...formItemLayout}>
              <TreeSelect treeDefaultExpandAll 
                dataSource={this.state.areaSource} 
                onChange={this.handleAreaChange} 
                style={{ width: 220 }} 
              />
            </FormItem>
          </Form>
        </Dialog>
      </div>
    );
  }
}

const styles = {
  editDialog: {
    display: 'inline-block',
    marginRight: '5px',
  },
};
